<template>
  <div class="role-card" :class="[hasChild ? 'highlight' : '']">
    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 8px 10px 20px;
        background-color: #f9fbfd;
        border-top-right-radius: 6px;
        border-top-left-radius: 6px;
      "
    >
      <div
        style="
          min-width: 0;
          color: #3d3d3d;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        "
      >
        <el-tooltip effect="dark" :content="role.roleName" placement="top">
          <div
            style="
              font-size: 16px;
              font-weight: 700;
              line-height: 26px;
              min-width: 0;
              color: #1a1a1a;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            "
          >
            {{ role.roleName }}
          </div>
        </el-tooltip>
        <div style="color: #aaaaaa; font-size: 12px; line-height: 14px">
          <i class="el-icon-user" style="font-size: 14px"></i>
          <span> + {{ role.userCounts }}</span>
        </div>
      </div>
      <div class="flex-none" style="width: 56px">
        <div
          v-if="loginUser.topOrgFlag === 1"
          v-permission="{ permission: '10408010.ROLE_MANAGE' }"
          class="role-card__btn"
          @click="handleEdit"
        >
          <svg-icon icon-class="edit_1" style="font-size: 16px" />
        </div>
        <div
          v-if="loginUser.topOrgFlag === 1"
          v-permission="{ permission: '10408010.ROLE_MANAGE' }"
          class="role-card__btn_delete"
          @click="handleDelete"
        >
          <svg-icon icon-class="delete_1" style="font-size: 16px" />
        </div>
      </div>
    </div>

    <div style="height: 300px">
      <el-empty v-if="role.userList.length === 0" :description="$t('common.empty_tip')" />
      <div v-else>
        <el-scrollbar style="height: 300px" wrap-style="overflow-x:hidden;">
          <div
            v-for="user in role.userList"
            :key="user.userId"
            class="user-list__item"
            :class="[user.userId === activeUser ? 'highlight-item' : '']"
          >
            <div style="display: flex; align-items: center; min-width: 0">
              <div style="position: relative; flex: none">
                <img
                  :class="[user.status === 0 ? 'user-lock' : '']"
                  style="height: 32px; width: 32px; margin-right: 12px"
                  :src="getLogo(user.logoUrl)"
                />
                <i
                  v-if="user.status === 0"
                  class="el-icon-lock"
                  style="
                    position: absolute;
                    top: 8px;
                    left: 8px;
                    font-size: 16px;
                    font-weight: 600;
                  "
                ></i>
              </div>
              <div style="min-width: 0">
                <div
                  style="
                    font-size: 14px;
                    color: #1a1a1a;
                    line-height: 20px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  "
                >
                  {{ user.name }}
                </div>
                <div
                  style="
                    font-size: 12px;
                    color: #aaaaaa;
                    line-height: 14px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  "
                >
                  {{ user.email }}
                </div>
              </div>
            </div>
            <div
              v-if="user.userId != loginUserId"
              v-permission="{
                permission: '10408010.USER_MANAGE',
              }"
            >
              <svg-icon
                icon-class="delete_1"
                class="role-card_del"
                @click="deleteUser(user)"
              />
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<script>
import { deleteRole } from "@/api/role";
import { addUser, editUser, getUser } from "@/api/user";
export default {
  props: {
    role: {
      type: Object,
      default: () => {
        return {
          userCounts: 0,
          roleName: "null",
        };
      },
    },
    activeUser: {
      type: Number,
      default: -1,
    },
  },
  computed: {
    hasChild() {
      return this.role.userList.find((user) => {
        return user.userId === this.activeUser;
      });
    },
  },
  data() {
    return {
      loginUser: {},
      loginUserId: "",
      addRoleVisible: false,
      operationType: "",
      editRoleId: "",
      form: {
        userId: "",
        queryOrg: {},
        createType: 0,
        orgId: null,
        username: "",
        name: "",
        email: null,
        mobile: "",
        countryCode: "",
        status: 1,
        roleList: [],
        roleIds: [],
      },
    };
  },
  mounted() {
    this.loginUser = JSON.parse(
      localStorage.getItem(this.$store.getters.keys.storage.username)
    );
    this.loginUserId = this.loginUser.userId;
  },
  methods: {
    deleteUser(user) {
      let userName = ` <span style="color:#409EFF">${user.name}</span>`;
      let roleName = ` <span style="color:#409EFF">${this.role.roleName}</span>`;
      this.$confirm(
        this.$t("user.user_delete_confirm", { userName, roleName }),
        this.$t("common.tips"),
        {
          confirmButtonText: this.$t("common.confirm"),
          cancelButtonText: this.$t("common.cancel"),
          type: "warning",
          dangerouslyUseHTMLString: true,
        }
      ).then(() => {
        this.$emit("update:listLoading", true);
        this.getUserInfo(user.userId);
      });
    },

    saveUser() {
      if (this.form.roleIds.length > 5) {
        console.log(this.form.roleIds);
        this.$message.error(this.$t("user.max_role_error"));
        return;
      }
      // role info
      this.form.roleList = [];
      this.form.roleIds.forEach((roleId) => {
        this.form.roleList.push({ roleId: roleId });
      });
      this.form.platCode = ["TOMS"];
      if (this.form.userId) {
        editUser(this.form)
          .then(() => {
            this.$message({
              message: this.$t("common.success"),
              type: "success",
            });
            this.$emit("refresh");
          })
          .catch((e) => {
            this.$confirmError(e);
          });
      }
    },
    getUserInfo(userId) {
      getUser(userId)
        .then((res) => {
          this.form.userId = userId;
          this.form.roleIds = [];
          this.form.username = res.username;
          this.form.orgId = res.orgId;
          this.form.name = res.name;
          this.form.email = res.email;
          this.form.mobile = res.mobile;
          this.form.countryCode = res.countryCode;
          this.form.status = res.status;
          console.log(res.roleList);
          if (res.roleList) {
            res.roleList.forEach((role) => {
              this.form.roleIds.push(role.roleId);
            });
          }
          this.form.roleIds = this.form.roleIds.filter(
            (roleId) => roleId !== this.role.roleId
          );
          console.log(this.form.roleIds);
          if (this.form.roleIds.length === 0) {
            this.$message.error(this.$t("user.min_role_error"));
            this.$emit("update:listLoading", false);
            return;
          }
          /* this.$nextTick(() => {
          this.$refs.organizationTree.initData()
        }) */
          this.saveUser();
        })
        .catch((err) => {
          this.$confirmError(err);
          this.$emit("update:listLoading", false);
        });
    },
    handleDelete() {
      this.$confirm(
        this.$t("role.role_delete_confirm") +
          ` <span style="color:#409EFF">${this.role.roleName}</span>?`,
        this.$t("common.tips"),
        {
          confirmButtonText: this.$t("common.confirm"),
          cancelButtonText: this.$t("common.cancel"),
          type: "warning",
          dangerouslyUseHTMLString: true,
        }
      ).then(() => {
        this.$emit("update:listLoading", true);
        deleteRole(this.role.roleId)
          .then(() => {
            this.$message({
              message: this.$t("role.delete_success"),
              type: "success",
            });
            this.refresh();
          })
          .catch((err) => {
            this.$confirmError(err);
            this.$emit("update:listLoading", false);
          });
      });
    },
    refresh() {
      this.$emit("refresh");
    },
    handleEdit() {
      this.$emit("role-edit");
    },
    getLogo(logo) {
      if (logo) {
        let avatars = this.$store.getters.avatars.find((v) => v.name == logo);
        if (avatars) {
          return avatars.src;
        }
      }
      return this.$store.getters.avatars[0].src;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.role-card {
  box-shadow: $boxShadow;
  margin-bottom: 20px;
  padding-bottom: 6px;
  border-radius: 6px;
  background-color: #fff;

  &:hover {
    box-shadow: rgba(17, 17, 26, 0.3) 0px 6px 16px;
    transition: all ease 0.3s;
    transform: translateY(-6px);
  }

  .role-card__btn {
    cursor: pointer;
    display: inline-block;
    padding: 4px;
    border-radius: 3px;
    color: #aaa;
    font-size: 16px;
    line-height: 16px;
    border: 1px solid #f9fbfd;
    border-radius: 3px;
    &:hover {
      border: 1px solid #b3d8ff;
      background-color: #ecf5ff;
      color: #409eff;
    }
  }
  .role-card__btn_delete {
    cursor: pointer;
    display: inline-block;
    padding: 4px;
    border-radius: 3px;
    color: #aaa;
    font-size: 16px;
    line-height: 16px;
    border: 1px solid #f9fbfd;
    border-radius: 3px;
    &:hover {
      border: 1px solid #fbc4c4;
      background-color: #fef0f0;
      color: #f56c6c;
    }
  }
  .role-card_del {
    cursor: pointer;
    display: inline-block;
    color: #aaaaaa;
    font-size: 18px;

    &:hover {
      color: #f87171;
    }
  }

  .user-list__item {
    padding: 8px 16px;
    border-bottom: 1px solid #e9edf3;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .user-lock {
      filter: grayscale(0.9) opacity(0.3);
    }

    img {
      margin-right: 5px;
      border-radius: 50%;
    }
  }

  .user-list__item:first-child {
    border-top: 1px solid #e9edf3;
  }

  .user-list__item_active,
  .user-list__item:hover {
    background-color: #f5f7fa;
  }
}

.highlight {
  outline: 2px solid var(--el-color-primary);
}
.highlight-item {
  background-color: #f2f6fc;
}
</style>
